#include "bat_manager.h"

//电池放电曲线
uint32_t bat_vot_lev[100] = 
{
    4094, 4080, 4069, 4059, 4050, 4042, 4034, 4024, 4019, 4008,
    3996, 3989, 3976, 3969, 3965, 3960, 3950, 3942, 3936, 3930,
    3923, 3917, 3913, 3905, 3900, 3890, 3882, 3877, 3869, 3865,
    3860, 3851, 3846, 3843, 3835, 3830, 3825, 3818, 3814, 3808,
    3805, 3799, 3795, 3791, 3788, 3785, 3782, 3780, 3775, 3773,
    3770, 3768, 3766, 3764, 3762, 3760, 3758, 3756, 3754, 3752,
    3750, 3748, 3746, 3744, 3742, 3740, 3738, 3736, 3734, 3732,
    3729, 3727, 3725, 3722, 3720, 3719, 3715, 3711, 3707, 3701,
    3696, 3691, 3685, 3683, 3677, 3669, 3663, 3659, 3655, 3653,
    3648, 3641, 3638, 3618, 3606, 3580, 3531, 3470, 3375, 3200,
};


//*****************************************************************************
// * 函 数 名  : bat_volt_to_percent
// * 函数功能  : 电压转电量百分比
// * 输入参数  :	 bat_volt： 电压
// * 输出参数  : 无
// * 返 回 值  : 电量：0-100
//*****************************************************************************/
uint8_t bat_volt_to_percent(uint32_t bat_volt)
{
    uint8_t bat_percent = 0;

    uint8_t i = 0;

    for (i = 0; i < 100; i++)
    {
        if (bat_volt >= bat_vot_lev[i])
        {
            bat_percent = 100 - i;
            break;
        }
    }

    if (100 == i)
    {
        bat_percent = 0;
    }

    return bat_percent;
}


// 电池电压范围定义
#define MIN_VOLTAGE 3.2f
#define MAX_VOLTAGE 4.2f

// 电量百分比计算函数
uint8_t calculate_battery_percentage(float voltage) {
    // 电压超出范围处理
    if (voltage <= MIN_VOLTAGE) {
        return 0;
    } else if (voltage >= MAX_VOLTAGE) {
        return 100;
    }
    
    // 线性计算电量百分比
    float percentage = (voltage - MIN_VOLTAGE) / (MAX_VOLTAGE - MIN_VOLTAGE) * 100.0f;
    
    // 确保百分比在0-100范围内
    if (percentage < 0) {
        return 0;
    } else if (percentage > 100) {
        return 100;
    }
    return (uint8_t)percentage;
}
